import { Service } from 'egg';
import { Feedback } from '../model/Feedback';

class FeedbackService extends Service {
    /**
     * 查询反馈列表
     * @param param 
     */
    public async searchFeedbackList(param: any) {
        const offset = (Number(param.page) - 1) * Number(param.size);
        const limit = Number(param.size);
        let actualParam: any = {};
        const Op = this.ctx.model.Op;
        if (param.feedback_title) {
            actualParam.feedback_title = { [Op.like]: '%' + param.feedback_title + '%' }
        }
        if (param.feedback_time_start && param.feedback_time_end) {
            actualParam.feedback_time = { [Op.between]: [param.feedback_time_start+' 00:00:00', param.feedback_time_end+' 23:59:59'] }
        }
        actualParam.is_delete = '1';
        const feedback = await this.ctx.model.Feedback.findAll<Feedback>({
            offset,
            limit,
            attributes: ['feedback_id', 'feedback_title', 'feedback_content', 'feedback_phone', 'feedback_picture', 'feedback_time'],
            where: actualParam,
            order: [['created_at', 'DESC']]
        });
        const count = await this.ctx.model.Feedback.count({
            where: actualParam,
        });
        if (feedback.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        const result = { count, feedbackList: feedback };
        return result;
    }

    /**
     * 新增问题反馈
     * @param param 
     */
    public async createFeedback(param: any) {
        param.feedback_id = this.ctx.helper.genUUID();
        const date = new Date();
        const dateStr = date.toLocaleString();
        param.feedback_time = dateStr;
        param.is_delete = '1';
        const resultFeedback = await this.ctx.model.Feedback.create(param);
        if (!resultFeedback) {
            throw new Error(JSON.stringify({ code: 2, msg: '问题反馈失败' }));
        }
    }
}
export default FeedbackService;